import * as types from "../types/bindMobileTypes";
import NetWorkUtil from "../utils/NetWorkUtil";
import { isEmpty } from "../utils/utils";
import ApiConstants from "../common/ApiConstants";
import { toastShort } from "../utils/ToastUtils";
import RegexUtil from "../utils/RegexUtil";

export function getSmsCode(mobile, type, callback) {
  return dispatch => {
    if (isEmpty(mobile)) {
      toastShort("请输入手机号");
      return;
    }
    if (!RegexUtil.checkMobile(mobile)) {
      toastShort("请输入正确的手机号");
      return;
    }
    dispatch({ type: types.BINDMOBILE_GETCODE_LOADING });
    const params = { mobile, type: 1 };
    NetWorkUtil.post(ApiConstants.SENDSMS, params)
      .then(res => {
        toastShort("短信验证码已发送");
        dispatch({ type: types.BINDMOBILE_GETCODE_DONE });
        callback(res);
      })
      .catch(error => {
        toastShort(error.message);
        dispatch({ type: types.BINDMOBILE_GETCODE_ERROR, error });
      });
  };
}

export function bindMobile(mobile, verify_code, callback) {
  return dispatch => {
    dispatch({ type: types.BINDMOBILE_LOADING });
    const params = { mobile, verify_code };
    NetWorkUtil.post(ApiConstants.BINDMOBILE, params)
      .then(res => {
        toastShort("手机号绑定成功");
        dispatch({ type: types.BINDMOBILE_DONE });
        callback(res);
      })
      .catch(error => {
        toastShort(error.message);
        dispatch({ type: types.BINDMOBILE_ERROR, error });
      });
  };
}

export function inputMobile(mobile) {
  return dispatch => {
    dispatch({ type: types.BINDMOBILE_INPUTMOBILE, mobile });
  };
}

export function inputCode(code) {
  return dispatch => {
    dispatch({ type: types.BINDMOBILE_INPUTCODE, code });
  };
}

export function countDown(countDownNum) {
  return dispatch => {
    if (countDownNum > 0) {
      dispatch({ type: types.BINDMOBILE_COUNTDOWN, countDownNum: `（${countDownNum}）` });
    } else {
      dispatch({ type: types.BINDMOBILE_REGETCODE });
    }
  };
}

export function bingMobileUnmount() {
  return dispatch => {
    dispatch({ type: types.BINDMOBILE_UNMOUNT });
  };
}

export function bingMobileGetCodeUnmount() {
  return dispatch => {
    dispatch({ type: types.BINDMOBILE_GETCODEUNMOUNT });
  };
}
